#include "basetcp.h"
#include <QDateTime>
#include <QDebug>
#include <QThread>
#include "config/constants.h"

BaseTcp::BaseTcp(QObject *parent)
{
    initConnect();
}

BaseTcp::~BaseTcp()
{

}

void BaseTcp::onSetting()
{

}

void BaseTcp::onConnect(QString ip, int port)
{
    LOG_INFO << "Tcp thread id = " << QThread::currentThread();
    connectToHost(ip, port);
    waitForConnected();
}

void BaseTcp::onSend(QString command)
{
    write(command.toStdString().c_str());
    LOG_INFO << "Send tcp command is " << command.toStdString();
}

void BaseTcp::onDisconnect()
{
    this->close();
}

void BaseTcp::onConnected()
{

}

void BaseTcp::onDisconnectd()
{

}

void BaseTcp::onRead()
{
//    qDebug() << "Read from socket.";
    QByteArray array = readAll();
    //LOG_INFO <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz") << " size = " << array.size();
    emit emitData(array);
    //LOG_INFO <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");

}

void BaseTcp::onError(QAbstractSocket::SocketError e)
{

}

void BaseTcp::onStateChange(QAbstractSocket::SocketState e)
{
    emit netStateSignals(e);
    //这边打log，网络连接和断开几次之后会卡死。
//    LOG_INFO << "Net State Change: " << e;
}

void BaseTcp::initConnect()
{
    connect(this, SIGNAL(readyRead()), this, SLOT(onRead()));
    connect(this, SIGNAL(disconnected()), this, SLOT(onDisconnectd()));
    connect(this, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
            this,
            SLOT(onError(QAbstractSocket::SocketError)));
    connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,
            SLOT(onStateChange(QAbstractSocket::SocketState)));

}
